package bg.cinema_system.utils;

import java.io.UnsupportedEncodingException;
import java.util.Properties;

import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;

public class SendMail {
	
	private static String USERNAME = "cinema_marto@abv.bg";
	private static String PASSWORD = "123456";
	
	public void sendEmailTo(String sendTo, String text, String mailSubject){
		final String username = USERNAME;
		final String password = PASSWORD;
		// Recipient's email ID needs to be mentioned.
		Properties properties = System.getProperties();
		// Setup mail server
		setMailPropresties(properties);
		// create a session with an Authenticator
		Session session = Session.getInstance(properties, new javax.mail.Authenticator() {
			protected PasswordAuthentication getPasswordAuthentication() {
				return new PasswordAuthentication(username, password);
			}
		});

		try {
			MimeMessage message = new MimeMessage(session);
			try {
				message.setFrom(new InternetAddress(username, USERNAME));
			} catch (UnsupportedEncodingException e) {
				message.setFrom(new InternetAddress(username));
			}
			message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(sendTo));
			message.setSubject(mailSubject);
			// create and fill the first message part
			MimeBodyPart mbp1 = new MimeBodyPart();
			mbp1.setText(text, "UTF-8", "html");
			// create the Multipart and add its parts to it
			MimeMultipart mp = new MimeMultipart();
			mp.addBodyPart(mbp1);

			message.setContent(mp);
			// Send message
			Transport.send(message);
		} catch (MessagingException e) { 
			e.printStackTrace();
		}
	}
	
	private static void setMailPropresties(Properties properties) {
		properties.setProperty("mail.smtp.host", "smtp.abv.bg");
		properties.setProperty("mail.smtp.auth", "true");
		properties.setProperty("mail.smtp.port", "465");
		properties.setProperty("mail.smtp.starttls.enable", "true");
		properties.setProperty("mail.smtp.ssl.enable", "true");
	}

}
